package com.zuozhj.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.zuozhj.entity.SysUser;
import com.zuozhj.service.ISysUserService;
import com.zuozhj.utils.JwtUtils;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailServiceImpl userDetailServiceImpl;

    @Autowired
    ISysUserService sysUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtils.getHeader());
        // System.out.println("------------------------------------------------------------------");
        // System.out.println(jwt);
        // System.out.println("------------------------------------------------------------------");
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return ;
        }
        
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim == null) {
            throw new JwtException("token 异常");
        }

        if (jwtUtils.isTokenExpired(claim)) {
            throw new JwtException("token 已过期");
        }

        String username = claim.getSubject();

        SysUser sysuser = sysUserService.getByUsername(username);

        // UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(claim, username, userDetailServiceImpl.getUserAuthority(sysuser.getId()));
        // principal.getName() 获取道下面一行中的username
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, claim, userDetailServiceImpl.getUserAuthority(sysuser.getId()));
        
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
       
    }
}
